<?php
/**
 * Model
 *
 * 모델 객체의 인스턴스 관리
 *
 * @package boot
 * @author  Platform Team
 */

class Model
{
    /**
     * 인스턴스
     */
    private static $instance = null;

    /**
     * 모델 인스턴스 관리
     */
    private static $aModel = array();

    /**
     * 기본 DSN 정보
     */
    private static $aDefaultDsn = false;

    /**
     * EXEC 타입 쿼리 실행 비활성화
     */
    private static $isExecDisabled = false;

    /**
     * singleton 객체 반환
     *
     * @return Model
     */
    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self;
        }

        return self::$instance;
    }

    /**
     * 인스턴스 반환
     *
     * @return Model
     */
    public static function instance()
    {
        return self::$instance;
    }

    /**
     * 인스턴스 파괴
     */
    public static function instancedel()
    {
        self::$instance = null;
        self::$aModel = array();
        self::$aDefaultDsn = false;
        self::$isExecDisabled = false;
    }

    /**
     * 초기화
     *
     * @param array $aDefaultDsn
     * @param boolean $isExecDisabled (기본 : false)
     * @return boolean
     */
    public function initialize($aDefaultDsn, $isExecDisabled=false)
    {
        if ($aDefaultDsn === null) {
            throw new Exception('Default DSN is not found', E_ERROR);
        }

        self::$aDefaultDsn = $aDefaultDsn;
        self::$isExecDisabled = ($isExecDisabled !== true) ? false : true;

        return true;
    }

    /**
     * 모델 객체 반환
     *
     * @param string $sClass   (클래스명)
     * @param array $aDsn      (DSN 정보)
     * @return mixed (object | boolean)
     */
    public function load($sClass, $aDsn=null)
    {
        if ($aDsn === null) {
            $aDsn = self::$aDefaultDsn;
        }

        if (isset($aDsn['instance_key'])) {
            $sKey = $sClass . $aDsn['instance_key'];
        } else {
            $sKey = $sClass . serialize($aDsn);
        }


        if ($aDsn['none_connect_pool'] === true) {

            $sKey = '__reserved_single_conn__';
            $aDsn['instance_key'] = $sKey;
            $aDsn['is_exec_disabled'] = self::$isExecDisabled;
            self::$aModel[$sKey] = new $sClass($aDsn);

        } else {

            if (isset(self::$aModel[$sKey]) === false) {
                $aDsn['is_exec_disabled'] = self::$isExecDisabled;
                self::$aModel[$sKey] = new $sClass($aDsn);
            }

        }

        return self::$aModel[$sKey];
    }
}
